﻿using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;


namespace ArcEngine.Input
{
	/// <summary>
	/// Handles keyboard
	/// </summary>
	public static class Keyboard
	{
		/// <summary>
		/// Init the device
		/// </summary>
		/// <returns></returns>
		public static bool Init(Control control)
		{
/*
			device = new Device(SystemGuid.Keyboard);
			if (device == null)
			{
				Log.Send(new LogEventArgs(LogLevel.Fatal, "Failed to acquier keyboard !", null));
				return false;
			}

			device.SetCooperativeLevel(control, CooperativeLevelFlags.Background  | CooperativeLevelFlags.NonExclusive);
			device.SetDataFormat(DeviceDataFormat.Keyboard);

			try
			{ 
				device.Acquire(); 
			}
			catch (DirectXException ex)
			{
				Log.Send(new LogEventArgs(LogLevel.Fatal, ex.Message, ex.StackTrace));
				//return false;
			}  
*/
			return true;
		}


		/// <summary>
		/// Release the device
		/// </summary>
		static internal void Release()
		{
/*
			if (device == null)
				return;

			device.Unacquire();
			device.Dispose();
			device = null;
*/
		}



		/// <summary>
		/// KeyDown event
		/// </summary>
		/// <param name="e"></param>
		internal static void KeyDown(PreviewKeyDownEventArgs e)
		{
			if (OnKeyDown != null)
				OnKeyDown(null, e);
		}


		/// <summary>
		/// KeyUp event
		/// </summary>
		/// <param name="e"></param>
		internal static void KeyUp(KeyEventArgs e)
		{
			if (Terminal.Enable && e.KeyCode == Terminal.ToggleKey)
				Terminal.Visible = true;

			if (OnKeyUp != null)
			    OnKeyUp(null, e);
		}

		/// <summary>
		/// Checks key state 
		/// </summary>
		/// <param name="key"></param>
		/// <returns></returns>
		public static bool IsKeyDown(Keys key)
		{
			return (GetKeyState((short)key) & keyDownBit) == keyDownBit;
		}
        [DllImport("user32.dll")]
		static extern ushort GetKeyState(short nVirtKey);
		const ushort keyDownBit = 0x80;


		#region Events

		/// <summary>
		///  Event fired when a KeyDown occur
		/// </summary>
		public static event EventHandler<PreviewKeyDownEventArgs> OnKeyDown;


		/// <summary>
		/// Event fired when a KeyUp occurs
		/// </summary>
		public static event EventHandler<KeyEventArgs> OnKeyUp;


		#endregion
	}

}
